package lib.bone.admin.controller.research;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lib.bone.access.module.dict.entity.NepuPropertyDict;
import lib.bone.admin.anno.FormLock;
import lib.bone.access.constant.ResearchTypeConst;
import lib.bone.nepudata.domain.dto.property.NepuPropertyAddDTO;
import lib.bone.nepudata.domain.dto.property.NepuPropertyQueryDTO;
import lib.bone.nepudata.domain.dto.property.NepuPropertyUpdateDTO;
import lib.bone.ext.draft.NepuDraft;
import lib.bone.ext.draft.NepuDraftService;
import lib.bone.access.config.cycle.NepuCycleService;
import lib.bone.access.module.dict.DictServiceCtl;
import lib.bone.access.module.oss.NepuResearchFileService;
import lib.bone.nepudata.domain.entity.NepuProperty;
import lib.bone.nepudata.service.ResearchServiceCtl;
import lib.bone.nepudata.service.impl.NepuPropertyServiceImpl;
import lib.bone.admin.anno.WebLog;
import lib.bone.admin.constant.MethodTypeConst;
import lib.bone.admin.domain.dto.FileUpdateDTO;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.common.core.redis.RedisCache;
import lib.bone.common.utils.JsonUtil;
import lib.bone.flow.domain.dto.FlowParam;
import lib.bone.flow.service.FlowWorkCtl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * @author: kindear
 * 知识产权
 */
@Slf4j
@RestController
@RequestMapping("nepu")
@Api(tags = "知识产权")
public class NepuPropertyController {

    @Autowired
    NepuDraftService draftService;

    @Autowired
    ResearchServiceCtl researchServiceCtl;

    @Autowired
    DictServiceCtl dictServiceCtl;

    @Autowired
    RedisCache redisCache;

    @Autowired
    NepuPropertyServiceImpl nepuPropertyService;

    @Autowired
    NepuResearchFileService nepuResearchFileService;

    @Autowired
    FlowWorkCtl flowWorkCtl;

    @Autowired
    NepuCycleService cycleService;

    /**
     * 表单校验
     * @param dto
     * @return
     */
    public String formValid(NepuPropertyAddDTO dto){
        // 表单重复性校验
        String errMsg = "";
//        Optional<NepuProperty> topicOp = nepuPropertyService.findByPropertyCode(
//                dto.getPropertyCode()
//        );
//        if (topicOp.isPresent()) {
//            errMsg = "存在重复记录";
//            return errMsg;
//        }
        Long operator = StpUtil.getLoginIdAsLong();
        Long firstAuthorId = dto.getFirstAuthorId();
        if (!firstAuthorId.equals(operator)&&
                !dto.getSecondAuthorId().equals(operator)){
            errMsg = "您不是第一或第二完成人，无法申报该项目";
            return errMsg;
        }
        return errMsg;
    }
    @PostMapping("properties/storage")
    @FormLock(lockKey = "PEOPERTY_STORE",needLogin = true)
    @ApiOperation(value = "暂存记录",notes = "")
    public ResponseDTO<Object> setStorage(@RequestBody  NepuPropertyAddDTO dto){
        Long userId = StpUtil.getLoginIdAsLong();
        NepuDraft draft = new NepuDraft();
        draft.setFormId(ResearchTypeConst.PROPERTY);
        draft.setStatus(1);
        draft.setUserId(userId);
        draft.setFormJsonStr(JsonUtil.obj2String(dto));
        return ResponseDTO.succData(draftService.saveOne(draft));
    }

    @GetMapping("properties/storage")
    @ApiOperation(value = "获取最新暂存")
    public ResponseDTO<Object> getStorage(){
        Long userId = StpUtil.getLoginIdAsLong();
        Optional<NepuDraft> draftOp = draftService.getLastDraft(userId,ResearchTypeConst.PROPERTY);
        if (!draftOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        NepuDraft draft = draftOp.get();
        return ResponseDTO.succData(JsonUtil.string2Obj(draft.getFormJsonStr(),NepuPropertyAddDTO.class));
    }

    @GetMapping("properties/storage/all")
    @ApiOperation(value = "获取全部暂存")
    public ResponseDTO<Object> getAllStorage(){
        Long userId = StpUtil.getLoginIdAsLong();
        List<NepuDraft> drafts = draftService.getFormAllDrafts(userId,ResearchTypeConst.PROPERTY);
        return ResponseDTO.succData(drafts);
    }


    @WebLog(module = "nepu-access")
    @PostMapping(value = "properties")
    @FormLock(lockKey = "PEOPERTY_FORM",needLogin = true)
    @ApiOperation(value = "新建记录",notes = "")
    public ResponseDTO<Object> saveOne(@RequestBody @Validated NepuPropertyAddDTO nepuPropertyAddDTO){
//        // PRE 重复性校验 -- 根据课题编码
//        Optional<NepuProperty> nepuPropertyOp = nepuPropertyService.findByPropertyCode(nepuPropertyAddDTO.getProholder());
//        if (nepuPropertyOp.isPresent()){
//            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"重复的知识产权编号");
//        }
        // 1. 获取当前登录用户ID -- 自动拦截未登录用户
        String operator = StpUtil.getLoginIdAsString();
        // 2. 表单校验
        String errMsg = formValid(nepuPropertyAddDTO);
        if (!Validator.isEmpty(errMsg)){
            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,errMsg);
        }
        String firstAuthorId = nepuPropertyAddDTO.getFirstAuthorId().toString();
        String secondAuthorId = nepuPropertyAddDTO.getSecondAuthorId().toString();
        if (firstAuthorId.equals("0")){
            // 第一作者为学生
            if (!operator.equals(secondAuthorId)){
                return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"用户不在参与人员中，无法申报");
            }
        }else {
            if (!operator.equals(firstAuthorId)){
                return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"您不是第一完成人,无法申报");
            }
        }
        // 重复拦截
        if (nepuPropertyAddDTO.getFirstAuthorId().equals(nepuPropertyAddDTO.getSecondAuthorId())){
            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"一二作者不可为同一人");
        }
        // 2. 获取当前时间所在周期ID -- 自动拦截不在时间段内的提交
//        String cycleId = cycleService.getNowCycleId();
        String cycleId = cycleService.getNowResearchCycleId();
        // 3. 获取词典信息
        Optional<Object> propertydictOp = dictServiceCtl.getById(nepuPropertyAddDTO.getPropertyDictId(),ResearchTypeConst.PROPERTY);
        if (!propertydictOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        }
        NepuPropertyDict dict = (NepuPropertyDict) propertydictOp.get();
        // 4. 写入记录 并赋值最大工作量
        NepuProperty saveEntity = new NepuProperty();
        saveEntity.setCycleId(cycleId);
        BeanUtil.copyProperties(nepuPropertyAddDTO,saveEntity,CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        saveEntity.setWorkload(dict.getWorkloadMax());
        NepuProperty property = (NepuProperty) researchServiceCtl.saveOne(saveEntity);
        // 5. 写入绑定文件信息 -- 修改为异步任务
//        List<String> fileIds = nepuPropertyAddDTO.getFileIds();
//        nepuResearchFileService.batchBindFile(ResearchTypeConst.PROPERTY,property.getId(),fileIds);
        // 6. 构建流程参数
        FlowParam flowParam = new FlowParam(ResearchTypeConst.PROPERTY,property.getId(),property.getPropertyName(),operator,null);
//        flowParam.setServiceType(ResearchTypeConst.PROPERTY);
//        flowParam.setServiceId(property.getId());
//        flowParam.setOperator(operator);

        //调用 FlowWorkCtl 启动一个流程实例
        // 获取当前登录用户ID
       // String operator = StpUtil.getLoginIdAsString();
        // 构造流程参数
//        flowParam.setServiceType(ResearchTypeConst.PROPERTY);
//        flowParam.setServiceId(property.getId());
//        flowParam.setServiceName(property.getPropertyName());
//        flowParam.setOperator(operator);
        // 7. 启动流程实例 -- 修改为异步任务
        flowWorkCtl.startProcess("property-check-01",operator,flowParam);
        return ResponseDTO.succData(property);
    }

    @WebLog(module = "nepu-access",operate = MethodTypeConst.UPDATE)
    @PutMapping(value = "properties")
    @ApiOperation(value = "更新单条记录",notes = "")
    public ResponseDTO<Object> updateOne(@RequestBody @Validated NepuPropertyUpdateDTO nepuPropertyUpdateDTO){
        Optional<Object> propertyOp = researchServiceCtl.getById(nepuPropertyUpdateDTO.getId(),ResearchTypeConst.PROPERTY);
        if (!propertyOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        }
        NepuProperty property = (NepuProperty) propertyOp.get();
        BeanUtil.copyProperties(nepuPropertyUpdateDTO,property,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        return ResponseDTO.succData(researchServiceCtl.updateOne(property,ResearchTypeConst.PROPERTY));
    }

    @GetMapping(value = "properties/{id}")
    @ApiOperation(value = "查询单条记录",notes = "")
    public ResponseDTO<Object> getOne(@PathVariable("id") String id){
        Optional<Object> entityOp = researchServiceCtl.getById(id,ResearchTypeConst.PROPERTY);
        return entityOp.map(ResponseDTO::succData).orElseGet(() -> ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND));
    }

    @WebLog(module = "nepu-access",operate = MethodTypeConst.DELETE)
    @DeleteMapping(value = "properties/{id}")
    @ApiOperation(value = "删除单条记录",notes = "")
    public ResponseDTO<Object> deleteOne(@PathVariable("id") String id){
        return researchServiceCtl.deleteById(id,ResearchTypeConst.PROPERTY);
    }


    @GetMapping(value = {"properties"})
    @ApiOperation(value = "查询全部",notes = "")
    public ResponseDTO<Object> getAll(NepuPropertyQueryDTO nepuPropertyQueryDTO){
        Sort sort;
        if(nepuPropertyQueryDTO.getOrder().equalsIgnoreCase("DESC")){
            sort = Sort.by(Sort.Direction.DESC, nepuPropertyQueryDTO.getSortBy());
        }else {
            sort = Sort.by(Sort.Direction.ASC, nepuPropertyQueryDTO.getSortBy());
        }

        // tips : 页码对应 - 1
        Pageable pageable = PageRequest.of(nepuPropertyQueryDTO.getPageNum() - 1 , nepuPropertyQueryDTO.getPageSize(), sort);

        NepuProperty nepuProperty = new NepuProperty();
        BeanUtil.copyProperties(nepuPropertyQueryDTO,nepuProperty, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        Example<NepuProperty> example = Example.of(nepuProperty);
        return ResponseDTO.succData(researchServiceCtl.getAll(pageable,example,ResearchTypeConst.PROPERTY));
    }

    @WebLog(module = "nepu-access",operate = MethodTypeConst.UPDATE)
    @PutMapping("properties/files")
    @ApiOperation(value = "更新附件信息",notes = "")
    public ResponseDTO<Object> updateFiles(@RequestBody @Validated FileUpdateDTO dto){
        Long userId = StpUtil.getLoginIdAsLong();
        Optional<Object> propertyOp = researchServiceCtl.getById(dto.getMapperId(),ResearchTypeConst.PROPERTY);
        if (!propertyOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        }
        NepuProperty property = (NepuProperty) propertyOp.get();
        if (!userId.equals(property.getFirstAuthorId())){
            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"非负责人无法修改");
        }
        // 清理之前的附件信息
        nepuResearchFileService.deleteEntityLink(property.getId());
        // 写入新的附件信息
        List<String> fileIds = dto.getFileIds();
        nepuResearchFileService.batchBindFile(ResearchTypeConst.PROPERTY,property.getId(),fileIds);
        // 返回操作信息
        return ResponseDTO.succMsg("更新成功");
    }

    @WebLog(module = "nepu-access",operate = MethodTypeConst.UPDATE)
    @PutMapping("properties/{id}/workload")
    @ApiOperation(value = "修改记录工作量")
    public ResponseDTO<Object> updateWorkload(@PathVariable("id") String id,@RequestParam("workload") Double workload){
        Optional<Object> entityOp = researchServiceCtl.getById(id,ResearchTypeConst.PROPERTY);
        if (!entityOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"未找到对应课题记录");
        }
        NepuProperty property = (NepuProperty) entityOp.get();
        String dictId = property.getPropertyDictId();
        Optional<Object> dictOp = dictServiceCtl.getById(dictId,ResearchTypeConst.PROPERTY);
        if (!dictOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"未找到课题关联词典记录");
        }
        NepuPropertyDict dict = (NepuPropertyDict) dictOp.get();
        if (workload > dict.getWorkloadMax() || workload < dict.getWorkloadMin()){
            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"工作量范围错误");
        }
        property.setWorkload(workload);
        // 写入记录
        return ResponseDTO.succData(researchServiceCtl.updateOne(property,ResearchTypeConst.PROPERTY));
    }
}
